'use strict';
// const hmac = require("hmac")
// const hashlib = require("hashlib")
const crypto = require('crypto');

module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/xcxzf/kh/hqcs.js 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			out_trade_no,
			total_fee,
			encryptedKey,
			pid
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		// 解密 sessionKey
		let decryptedRes = vk.crypto.aes.decrypt({
			data: encryptedKey, // 待解密的原文
		});
		let sessionKey = decryptedRes.sessionKey;

		// 数据库查询 对应小程序的虚拟支付参数
		let result = await vk.baseDao.selects({
			dbName: "vk-pay-config",
			// 主表where条件
			whereJson: {
				_id:pid
			},
		})
		 
		console.log('获取AppKey',result.rows[0].wxpay["mp-weixin"].AppKey);
		console.log('获取OfferID',result.rows[0].wxpay["mp-weixin"].OfferID);
		
		let AppKey = result.rows[0].wxpay["mp-weixin"].AppKey
		let OfferID = result.rows[0].wxpay["mp-weixin"].OfferID


		let uri = "requestVirtualPayment" // 默认

		// 使用对象字面量的方式构造 post_body
		let post_body = JSON.stringify({
			offerId: OfferID, // 虚拟支付应用ID
			buyQuantity: Number(data.total_fee), // 充值金额(数量)
			currencyType: "CNY", // 默认
			platform: "android", // 默认
			outTradeNo: out_trade_no // 订单号
		});

		res.postbody = JSON.stringify({
			offerId: OfferID,
			buyQuantity: Number(data.total_fee),
			currencyType: "CNY",
			platform: "android",
			outTradeNo: out_trade_no
		});


		// 调用支付签名
		res.paySig = calc_pay_sig(uri, post_body, AppKey)

		// 调用用户态签名
		res.signature = calc_signature(post_body, sessionKey)

		// 业务逻辑结束-----------------------------------------------------------
		return res;


		function calc_pay_sig(uri, post_body, AppKey) {
			const need_sign_msg = uri + '&' + post_body;
			const pay_sig = crypto.createHmac('sha256', AppKey).update(need_sign_msg).digest('hex');
			return pay_sig;
		}

		function calc_signature(post_body, sessionKey) {
			const need_sign_msg = post_body;
			const signature = crypto.createHmac('sha256', sessionKey).update(need_sign_msg).digest('hex');
			return signature;
		}
	}
}